/**
 * 发布订阅模式实现非父子组件通信
 */
import React, { Component } from 'react'
import axios from 'axios'
import '../css/05_non_father_son.css'

var bus = {
    list: [],
    subscribe(callback) {
        this.list.push(callback)
    },

    publish(value) {
        this.list.forEach(callback => {
            callback && callback(value);
        })
    }

}
class FilmItem extends React.Component {
    render() {
        let { name, poster, grade, synopsis } = this.props;
        return (
            <div className="filmItem" onClick={() => {
                bus.publish(synopsis)
            }}>
                <img src={poster} alt={name} />
                <h4>{name}</h4>
                <div>观众评分： {grade}</div>
            </div>
        )
    }
}
class FilmDetail extends React.Component {
    constructor() {
        super()
        this.state = {
            info: ""
        }
        bus.subscribe((value) => {
            this.setState({
                info: value
            })
        })
    }
    render() {
        return (
            <div className="filmDetail">
                {this.state.info}
            </div>
        )
    }
}
export default class App extends Component {
    constructor() {
        super()
        this.state = {
            filmList: [],
        }
        axios.get("/test.json").then(res => {
            console.log(res.data.data.films);
            this.setState({ filmList: res.data.data.films })
        })
    }
    render() {
        return (
            <div>
                {
                    this.state.filmList.map(item =>
                        <FilmItem key={item.filmId} {...item}></FilmItem>
                    )
                }
                <FilmDetail></FilmDetail>
            </div>
        )
    }
}

